import React from 'react';
import { Select } from 'antd';

const { Option } = Select;

class SelfSelect extends React.Component {
  static defaultProps = {
    cache: true,
  };

  static getDerivedStateFromProps(nextProps) {
    if ('value' in nextProps) {
      return { value: nextProps.value };
    }
    return null;
  }

  constructor(props) {
    super(props);

    this.state = {
      value: props.value,
    };
  }

  componentDidMount() {
    const { options, cache } = this.props;
    if (!cache || !(options && options.length)) {
      this.props.getData();
    }
  }

  handleChange = value => {
    if (!('value' in this.props)) {
      this.setState({ value });
    }
    this.triggerChange(value);
  };

  triggerChange = changedValue => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  render() {
    const { value } = this.state;
    const { options, renderOption, placeholder, ...others } = this.props;
    return (
      <Select {...others} value={value || 0} onChange={this.handleChange}>
        <Option value={0}>{placeholder || '未选择'}</Option>
        {options && options.length > 0 ? (
          options.map(renderOption(Option))
        ) : (
          <Option value={1} disabled>
            暂无数据
          </Option>
        )}
      </Select>
    );
  }
}

export default SelfSelect;
